package com;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DayTimeClient2 {

    public static void main(String[] args) {

        String hostname = args.length>0?args[0]:"time.nist.gov";

        try (Socket socket = new Socket(hostname,13)){

            socket.setSoTimeout(15000);

            InputStream in = socket.getInputStream();

            Reader reader = new InputStreamReader(in,"ASCII");

            StringBuilder stringBuilder = new StringBuilder();

            int c;

            while ((c=reader.read()) != -1)
                stringBuilder.append((char)c);

            Date date = formatDate(stringBuilder.toString());

            System.out.println(date);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    private static Date formatDate(String s) throws ParseException {

        String[] time = s.split(" ");

        String daytime = time[1] + " " + time[2] + " UTC";

        DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd hh:mm:ss z");

        return dateFormat.parse(daytime);

    }


}
